package com.dc.server.pay.factory;

import com.dc.server.pay.Pay;
import com.dc.server.pay.strategy.BankStrategy;
import org.aspectj.weaver.reflect.ReflectionShadow;
import org.reflections.Reflections;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Set;

/**`
 * @Auther: 赵聪
 * @Date: 2018/8/25 09:25
 * @Description: 策略工厂  生产某个特定的策略
 */
public class StartegyFactory {

    private static HashMap<String, String> sourceMap = new HashMap<>();
    private static StartegyFactory factory = null;
    // TODO 这里的扫码会影响spring的注入
    static {
        //反射工具包，扫码策略包
        Reflections reflections = new Reflections("com.dc.server.pay.strategy.impl");
        //获取加了pay的注解类
        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Pay.class);
        //根据注解值，把类名放到map
        for (Class cs : typesAnnotatedWith) {
            Pay pay = (Pay) cs.getAnnotation(Pay.class);
            sourceMap.put(pay.value(), cs.getCanonicalName());

        }
    }


    private StartegyFactory() {
    }

    public BankStrategy creator(String type) {
        String clazz = sourceMap.get(type);
        BankStrategy bankStrategy = null;
        try {
            Class<?> aClass = Class.forName(clazz);
            bankStrategy = (BankStrategy) aClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bankStrategy;
    }

    public static StartegyFactory getInstance() {
        if (factory == null) {
            return new StartegyFactory();
        }
        return factory;
    }
}
